import React, { useState } from 'react';
import {
  Card,
  Table,
  Button,
  Modal,
  Form,
  Input,
  Select,
  Tag,
  Space,
  Typography,
  Row,
  Col,
  message,
  Rate,
  Progress,
} from 'antd';
import {
  PlusOutlined,
  CustomerServiceOutlined,
  StarOutlined,
  EditOutlined,
  DeleteOutlined,
  EyeOutlined,
  PlayCircleOutlined,
} from '@ant-design/icons';
import SongFormModal from './Songs/SongFormModal';
import SongDetailModal from './Songs/SongDetailModal';
import SongPracticeModal from './Songs/SongPracticeModal';

const { Title } = Typography;
const { Option } = Select;
const { TextArea } = Input;

const Songs = () => {
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isDetailModalVisible, setIsDetailModalVisible] = useState(false);
  const [isPracticeModalVisible, setIsPracticeModalVisible] = useState(false);
  const [editingSong, setEditingSong] = useState(null);
  const [selectedSong, setSelectedSong] = useState(null);
  const [searchText, setSearchText] = useState('');
  const [filterDifficulty, setFilterDifficulty] = useState('all');
  const [form] = Form.useForm();
  const [practiceForm] = Form.useForm();

  // 模拟数据
  const [songs, setSongs] = useState([
    {
      key: '1',
      name: '夜空中最亮的星',
      artist: '逃跑计划',
      category: '流行',
      difficulty: 3,
      practiceCount: 12,
      mastery: 85,
      lastPractice: '2024-01-18',
      notes: '主歌部分需要加强练习',
      status: 'active',
    },
    {
      key: '2',
      name: '海阔天空',
      artist: 'Beyond',
      category: '摇滚',
      difficulty: 5,
      practiceCount: 8,
      mastery: 60,
      lastPractice: '2024-01-15',
      notes: '副歌部分配合需要改进',
      status: 'active',
    },
    {
      key: '3',
      name: '光辉岁月',
      artist: 'Beyond',
      category: '摇滚',
      difficulty: 4,
      practiceCount: 10,
      mastery: 75,
      lastPractice: '2024-01-16',
      notes: '整体表现良好',
      status: 'active',
    },
    {
      key: '4',
      name: '童话',
      artist: '光良',
      category: '流行',
      difficulty: 2,
      practiceCount: 15,
      mastery: 95,
      lastPractice: '2024-01-17',
      notes: '已熟练掌握',
      status: 'active',
    },
  ]);

  const columns = [
    {
      title: '歌曲名称',
      dataIndex: 'name',
      key: 'name',
      render: (text) => <a>{text}</a>,
    },
    {
      title: '艺术家',
      dataIndex: 'artist',
      key: 'artist',
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
      render: (category) => <Tag color="blue">{category}</Tag>,
    },
    {
      title: '难度',
      dataIndex: 'difficulty',
      key: 'difficulty',
      render: (difficulty) => (
        <div>
          <Rate disabled defaultValue={difficulty} style={{ fontSize: 12 }} />
          <div style={{ fontSize: 12, color: '#666' }}>
            {difficulty === 1 && '简单'}
            {difficulty === 2 && '较简单'}
            {difficulty === 3 && '中等'}
            {difficulty === 4 && '较困难'}
            {difficulty === 5 && '困难'}
          </div>
        </div>
      ),
    },
    {
      title: '练习次数',
      dataIndex: 'practiceCount',
      key: 'practiceCount',
      render: (count) => <Tag color="green">{count} 次</Tag>,
    },
    {
      title: '掌握程度',
      dataIndex: 'mastery',
      key: 'mastery',
      render: (mastery) => (
        <div>
          <Progress percent={mastery} size="small" />
          <div style={{ fontSize: 12, color: '#666' }}>{mastery}%</div>
        </div>
      ),
    },
    {
      title: '最后练习',
      dataIndex: 'lastPractice',
      key: 'lastPractice',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="link"
            icon={<EyeOutlined />}
            onClick={() => handleView(record)}
          >
            详情
          </Button>
          <Button
            type="link"
            icon={<PlayCircleOutlined />}
            onClick={() => handlePractice(record)}
          >
            练习
          </Button>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  const handleView = (record) => {
    setSelectedSong(record);
    setIsDetailModalVisible(true);
  };

  const handlePractice = (record) => {
    setSelectedSong(record);
    setIsPracticeModalVisible(true);
  };

  const handleEdit = (record) => {
    setEditingSong(record);
    form.setFieldsValue(record);
    setIsModalVisible(true);
  };

  const handleDelete = (record) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除歌曲 "${record.name}" 吗？`,
      onOk() {
        setSongs(songs.filter(item => item.key !== record.key));
        message.success('删除成功');
      },
    });
  };

  const handleAdd = () => {
    setEditingSong(null);
    setIsModalVisible(true);
  };

  const handleModalOk = (songData) => {
    if (editingSong) {
      setSongs(songs.map(item => 
        item.key === editingSong.key ? { ...item, ...songData } : item
      ));
      message.success('更新成功');
    } else {
      setSongs([...songs, songData]);
      message.success('添加成功');
    }

    setIsModalVisible(false);
    setEditingSong(null);
    form.resetFields();
  };

  const handleModalCancel = () => {
    setIsModalVisible(false);
    setEditingSong(null);
    form.resetFields();
  };

  const handleDetailModalCancel = () => {
    setIsDetailModalVisible(false);
    setSelectedSong(null);
  };

  const handlePracticeModalOk = (practiceData) => {
    // 更新歌曲的练习统计
    setSongs(songs.map(item => 
      item.key === practiceData.songId 
        ? { 
            ...item, 
            practiceCount: item.practiceCount + 1,
            lastPractice: practiceData.date,
            mastery: Math.min(100, item.mastery + Math.floor(practiceData.rating * 2))
          }
        : item
    ));
    
    message.success(`练习完成: ${practiceData.songName}`);
    setIsPracticeModalVisible(false);
    setSelectedSong(null);
    practiceForm.resetFields();
  };

  const handlePracticeModalCancel = () => {
    setIsPracticeModalVisible(false);
    setSelectedSong(null);
    practiceForm.resetFields();
  };

  const filteredSongs = songs.filter(item => {
    const matchesSearch = item.name.toLowerCase().includes(searchText.toLowerCase()) ||
                         item.artist.toLowerCase().includes(searchText.toLowerCase());
    const matchesDifficulty = filterDifficulty === 'all' || 
                             (filterDifficulty === 'easy' && item.difficulty <= 2) ||
                             (filterDifficulty === 'medium' && item.difficulty === 3) ||
                             (filterDifficulty === 'hard' && item.difficulty >= 4);
    return matchesSearch && matchesDifficulty;
  });

  return (
    <div>
      <Title level={2}>歌曲库</Title>

      {/* 搜索和过滤 */}
      <Card style={{ marginBottom: 16 }}>
        <Row gutter={16} align="middle">
          <Col xs={24} sm={12} md={8}>
            <Input
              placeholder="搜索歌曲名称或艺术家"
              allowClear
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              prefix={<CustomerServiceOutlined />}
            />
          </Col>
          <Col xs={24} sm={12} md={6}>
            <Select
              placeholder="选择难度"
              style={{ width: '100%' }}
              value={filterDifficulty}
              onChange={setFilterDifficulty}
            >
              <Option value="all">全部难度</Option>
              <Option value="easy">简单 (1-2星)</Option>
              <Option value="medium">中等 (3星)</Option>
              <Option value="hard">困难 (4-5星)</Option>
            </Select>
          </Col>
          <Col xs={24} sm={24} md={10}>
            <Space>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={handleAdd}
              >
                添加歌曲
              </Button>
              <Button icon={<StarOutlined />}>
                收藏夹
              </Button>
            </Space>
          </Col>
        </Row>
      </Card>

      {/* 统计信息 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
        <Col xs={24} sm={8}>
          <Card size="small">
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: 24, fontWeight: 'bold', color: '#1890ff' }}>
                {songs.length}
              </div>
              <div>总歌曲数</div>
            </div>
          </Card>
        </Col>
        <Col xs={24} sm={8}>
          <Card size="small">
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: 24, fontWeight: 'bold', color: '#52c41a' }}>
                {Math.round(songs.reduce((sum, song) => sum + song.mastery, 0) / songs.length)}
              </div>
              <div>平均掌握度</div>
            </div>
          </Card>
        </Col>
        <Col xs={24} sm={8}>
          <Card size="small">
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: 24, fontWeight: 'bold', color: '#faad14' }}>
                {songs.reduce((sum, song) => sum + song.practiceCount, 0)}
              </div>
              <div>总练习次数</div>
            </div>
          </Card>
        </Col>
      </Row>

      {/* 歌曲列表 */}
      <Card>
        <Table
          columns={columns}
          dataSource={filteredSongs}
          pagination={{
            total: filteredSongs.length,
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) =>
              `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
          }}
        />
      </Card>

      {/* 添加/编辑歌曲模态框 */}
      <SongFormModal
        visible={isModalVisible}
        onCancel={handleModalCancel}
        onOk={handleModalOk}
        editingSong={editingSong}
        form={form}
      />

      {/* 歌曲详情模态框 */}
      <SongDetailModal
        visible={isDetailModalVisible}
        onCancel={handleDetailModalCancel}
        onEdit={handleEdit}
        onPractice={handlePractice}
        selectedSong={selectedSong}
      />

      {/* 歌曲练习模态框 */}
      <SongPracticeModal
        visible={isPracticeModalVisible}
        onCancel={handlePracticeModalCancel}
        onOk={handlePracticeModalOk}
        selectedSong={selectedSong}
        form={practiceForm}
      />
    </div>
  );
};

export default Songs; 